package com.bkgy.controller.tcoilslit.service.impl;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.anno.Log;
import com.bkgy.commom.model.QueryDTO;
import com.bkgy.config.BusinessException;
import com.bkgy.controller.tcoilslit.dto.OptimizationSearchCondition;
import com.bkgy.controller.tcoilslit.entity.TCoilSlit;
import com.bkgy.controller.tcoilslit.mapper.OptimizationMapper;
import com.bkgy.controller.tcoilslit.service.OptimizationService;
import com.bkgy.sys.common.entity.ResultData;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
@Transactional
public class OptimizationServiceImpl extends ServiceImpl<OptimizationMapper, TCoilSlit> implements OptimizationService {

    @Resource
    private HttpServletResponse response;

    @Override
    public ResultData<Void> add(TCoilSlit tCoilSlit) {
        save(tCoilSlit);
        return ResultData.ResultDataSuccessSelf("添加成功", null);
    }

    @Override
    @Log(module = "分卷", description = "分卷列表分页查询")
    public ResultData<Page<TCoilSlit>> page(QueryDTO<OptimizationSearchCondition> queryDTO) {
        OptimizationSearchCondition condition = queryDTO.getDto();
        LambdaQueryWrapper<TCoilSlit> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(TCoilSlit::getIndocno);
        // 构建查询条件
        if (condition != null) {
            wrapper.like(StringUtils.hasText(condition.getEntId()), TCoilSlit::getEntId, condition.getEntId());
            wrapper.like(StringUtils.hasText(condition.getProductLine()), TCoilSlit::getProductLine, condition.getProductLine());
            wrapper.like(StringUtils.hasText(condition.getOrderNo()), TCoilSlit::getOrderNo, condition.getOrderNo());
            wrapper.like(StringUtils.hasText(condition.getSteelGrade()), TCoilSlit::getSteelGrade, condition.getSteelGrade());
            wrapper.eq(StringUtils.hasText(condition.getWtMisMatchFlag()) && condition.getWtMisMatchFlag().equals("0"), TCoilSlit::getWtMisMatchFlag, 0);
            wrapper.ne(StringUtils.hasText(condition.getWtMisMatchFlag()) && !condition.getWtMisMatchFlag().equals("0"), TCoilSlit::getWtMisMatchFlag, 0);
        }
        Page<TCoilSlit> page = new Page<>(queryDTO.getPage().getPageIndex(), queryDTO.getPage().getPageSize());
        Page<TCoilSlit> result = page(page, wrapper);
        return ResultData.ResultDataSuccess(result, (int) result.getTotal());
    }

    @Override
    public ResultData<Void> delete(Integer indocno) {
        TCoilSlit tCoilSlit = getById(indocno);
        if (tCoilSlit == null) {
            throw new BusinessException("要删除的数据不存在");
        }
        removeById(indocno);
        return ResultData.ResultDataSuccessSelf("删除成功", null);
    }

    @Override
    public ResultData<Void> update(TCoilSlit tCoilSlit) {
        TCoilSlit existTCoilSlit = getById(tCoilSlit.getIndocno());
        if (existTCoilSlit == null) {
            throw new BusinessException("要修改的数据字典不存在");
        }
        updateById(tCoilSlit);
        return ResultData.ResultDataSuccessSelf("修改成功", null);
    }
    
    @Override
    public void export(QueryDTO<OptimizationSearchCondition> queryDTO) {
        try {
            // 获取所有数据而不是分页数据
            OptimizationSearchCondition condition = queryDTO.getDto();
            LambdaQueryWrapper<TCoilSlit> wrapper = new LambdaQueryWrapper<>();
            
            if (condition != null) {
                wrapper.like(StringUtils.hasText(condition.getEntId()), TCoilSlit::getEntId, condition.getEntId());
                wrapper.like(StringUtils.hasText(condition.getProductLine()), TCoilSlit::getProductLine, condition.getProductLine());
                wrapper.like(StringUtils.hasText(condition.getOrderNo()), TCoilSlit::getOrderNo, condition.getOrderNo());
                wrapper.like(StringUtils.hasText(condition.getSteelGrade()), TCoilSlit::getSteelGrade, condition.getSteelGrade());
            }
            
            // 查询符合条件的所有数据
            List<TCoilSlit> dataList = list(wrapper);
            
            // 设置导出参数
            ExportParams exportParams = new ExportParams("生产计划动态切分建议", "生产计划动态切分建议", ExcelType.XSSF);
            
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TCoilSlit.class, dataList);
            
            // 行列固定
            if (workbook.getNumberOfSheets() > 0) {
                workbook.getSheetAt(0).createFreezePane(3, 2);
            }
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("生产计划动态切分建议", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }
}
